<?php

namespace App\Jobs\QiPao\Draw;

use App\Jobs\Job;
use App\Repositories\GiftRepository;
use App\Services\Draw\DrawConst\CacheKey;
use App\Services\Draw\Enum\DrawEnum;
use Illuminate\Support\Facades\Log;

class FantasyDrawStatisticsJob extends Job
{
    protected $statisticsData;
    protected $poolGroup;
    protected $user;
    protected $cachePrefix;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($poolGroup, $user, $statisticsData, $cachePrefix)
    {
        $this->statisticsData = $statisticsData;
        $this->poolGroup      = $poolGroup;
        $this->user           = $user;
        $this->cachePrefix    = $cachePrefix;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //Log::info('抽奖统计：' . json_encode($this->statisticsData));
        $date  = date('Ymd');
        $week  = date('YW');
        $month = date('Ym');
        $year  = date('Y');
        $redisObject = app('redis')->connection('game');
        try {

            // if ($this->poolGroup->tag == DrawEnum::POOL_TYPE_QUEUE) {
            //队列数据统计

            //已使用
            $poolConfig        = app('model_fantasy_pool_config')->one(['id' => 1], ['balance_coin']);
            $poolQueueTable    = app('model_fantasy_pool_queue')->getTable();
            $poolTemplateTable = app('model_fantasy_pool_template')->getTable();
            $giftTemplateTable = app('model_fantasy_gift_template')->getTable();
            $usedQueueData     = app('model_fantasy_pool_queue')->select([$poolQueueTable . '.id', 'draw_count', 'gift_id', $poolTemplateTable . '.count'])
                ->leftJoin($poolTemplateTable,
                    $poolQueueTable . '.group_id', '=', $poolTemplateTable . ".group_id")
                ->leftJoin($giftTemplateTable,
                    'gift_template_id', '=', $giftTemplateTable . ".id")
                ->where(['status' => 1])->orderBy($poolQueueTable . '.id')->get();
            $usedGiftIds       = $usedQueueData->pluck('gift_id')->toArray();
            //未使用
            $unusedQueueData = app('model_fantasy_pool_queue')->select([$poolQueueTable . '.id', 'draw_count', 'gift_id', $poolTemplateTable . '.count'])
                ->leftJoin($poolTemplateTable,
                    $poolQueueTable . '.group_id', '=', $poolTemplateTable . ".group_id")
                ->leftJoin($giftTemplateTable,
                    'gift_template_id', '=', $giftTemplateTable . ".id")
                ->where(['status' => 0])->orderBy($poolQueueTable . '.id')->get();
            $unusedGiftIds   = $unusedQueueData->pluck('gift_id')->toArray();

            $giftList       = (new GiftRepository())->giftsByIdsWithField(array_merge($usedGiftIds, $unusedGiftIds), ['id', 'price']);
            $giftListWithId = $giftList->keyBy('id');

            $usedCount     = 0;
            $usedOutput    = 0;
            $queueId       = 0;
            $usedDrawCount = 0;
            foreach ($usedQueueData as $usedData) {
                if ($usedData['id'] != $queueId) {
                    $usedDrawCount += $usedData['draw_count'];
                    $queueId       = $usedData['id'];
                    $usedCount++;
                }


                if (!empty($usedData['gift_id'])) {
                    $usedOutput += $usedData['count'] * $giftListWithId[$usedData['gift_id']]['price'];
                }
            }
            $usedInput       = $usedDrawCount * $poolConfig['balance_coin'];
            $unusedCount     = 0;
            $unusedOutput    = 0;
            $queueId         = 0;
            $unusedDrawCount = 0;
            foreach ($unusedQueueData as $unusedData) {
                if ($unusedData['id'] != $queueId) {
                    $unusedDrawCount += $unusedData['draw_count'];
                    $queueId         = $unusedData['id'];
                    $unusedCount++;
                }


                if (!empty($unusedData['gift_id'])) {
                    $unusedOutput += $unusedData['count'] * $giftListWithId[$unusedData['gift_id']]['price'];
                }
            }
            $unusedInput = $unusedDrawCount * $poolConfig['balance_coin'];
            app('model_lottery_fantasy_queue_statistics')->updateOrCreate(['id' => 1],
                ['unused_input' => $unusedInput, 'unused_output' => $unusedOutput, 'unused_count' => $unusedCount,
                 'used_input'   => $usedInput, 'used_output' => $usedOutput, 'used_count' => $usedCount]);

            //}
            //数据统计
            $userId = $this->user->user_id;
            $redisObject->setbit($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_DATE . "_" . $date, $userId, 1);
            $redisObject->setbit($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_WEEK . "_" . $week, $userId, 1);
            $redisObject->setbit($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_MONTH . "_" . $month, $userId, 1);
            $redisObject->setbit($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_YEAR . "_" . $year, $userId, 1);


            //数据统计
            $dateStatistics             = app('model_lottery_fantasy_statistics')->firstOrCreate(['time' => $date, 'type' => 1], ['time' => $date, 'type' => 1]);
            $weekStatistics             = app('model_lottery_fantasy_statistics')->firstOrCreate(['time' => $week, 'type' => 2], ['time' => $date, 'type' => 1]);
            $monthStatistics            = app('model_lottery_fantasy_statistics')->firstOrCreate(['time' => $month, 'type' => 3], ['time' => $date, 'type' => 1]);
            $yearStatistics             = app('model_lottery_fantasy_statistics')->firstOrCreate(['time' => $year, 'type' => 4], ['time' => $date, 'type' => 1]);
            $dateStatistics->input      += $this->statisticsData['input'];
            $dateStatistics->output     += $this->statisticsData['output'];
            $dateStatistics->count      += $this->statisticsData['count'];
            $dateStatistics->user_count = $redisObject->bitcount($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_DATE . "_" . $date);
            $dateStatistics->save();

            $weekStatistics->input      += $this->statisticsData['input'];
            $weekStatistics->output     += $this->statisticsData['output'];
            $weekStatistics->count      += $this->statisticsData['count'];
            $weekStatistics->user_count = $redisObject->bitcount($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_WEEK . "_" . $week);

            $weekStatistics->save();

            $monthStatistics->input      += $this->statisticsData['input'];
            $monthStatistics->output     += $this->statisticsData['output'];
            $monthStatistics->count      += $this->statisticsData['count'];
            $monthStatistics->user_count = $redisObject->bitcount($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_MONTH . "_" . $month);
            $monthStatistics->save();

            $yearStatistics->input      += $this->statisticsData['input'];
            $yearStatistics->output     += $this->statisticsData['output'];
            $yearStatistics->count      += $this->statisticsData['count'];
            $yearStatistics->user_count = $redisObject->bitcount($this->cachePrefix . CacheKey::USER_STATISTICS_COUNT_YEAR . "_" . $year);
            $yearStatistics->save();

            if ($this->poolGroup->tag == DrawEnum::POOL_TYPE_NOVICE) {
                //新手模板计算盈亏
                $poolConfig = app('model_fantasy_pool_config')->one(['id' => 1], ['balance_coin']);
                $noviceGiftTemplateList = app('model_fantasy_pool_group')->listWithTemplateGift(['pool_id'     => $this->poolGroup->pool_id, app('model_fantasy_pool_group')->getTable() . '.type' => DrawEnum::POOL_GROUP_TYPE_PRESET,
                                                                                                  'preset_type' => DrawEnum::PRESET_NOVICE_TYPE, 'status' => 1], ['group_id', 'gift_id', 'is_earning', app('model_fantasy_pool_template')->getTable() . '.count']);

                $giftIds               = $noviceGiftTemplateList->pluck('gift_id');
                $gifts                 = (new GiftRepository())->giftsByIdsWithField($giftIds, ['id', 'price']); // 抽中礼物信息
                $giftsWithId           = $gifts->keyBy('id');
                $noviceGroupUpdateData = [];
                $groupId               = 0;
                $sumOutput             = 0;
                $sumInput              = 0;
                $isEarning             = 0;
                $groupIsEarning        = null;
                foreach ($noviceGiftTemplateList as $template) {
                    if ($template->group_id != $groupId) {
                        if ($groupId != 0) {
                            if ($sumOutput > $sumInput) {
                                $isEarning = 0;
                            } else {
                                $isEarning = 1;
                            }
                            if ($isEarning !== $groupIsEarning) {
                                $noviceGroupUpdateData[$groupId]['is_earning'] = $isEarning;
                            }
                        }

                        $sumOutput      = 0;
                        $sumInput       = 0;
                        $groupId        = $template->group_id;
                        $groupIsEarning = $template->is_earning;
                    }
                    $sumOutput += $template->count * (isset($giftsWithId[$template->gift_id]) ? $giftsWithId[$template->gift_id]['price'] : 0);

                    $sumInput  += $template->count * $poolConfig->balance_coin;
                }

                if ($sumOutput > $sumInput) {
                    $isEarning = 0;
                } else {
                    $isEarning = 1;
                }
                if ($isEarning !== $groupIsEarning) {
                    $noviceGroupUpdateData[$groupId]['is_earning'] = $isEarning;
                }
                //Log::info('抽奖' . json_encode($noviceGroupUpdateData));
                app('model_fantasy_pool_group')->batchUpdateEarning($noviceGroupUpdateData);
            }
        } catch (\Exception $e) {
            Log::error('抽奖统计错误：' . $e->getMessage());
        }

    }

    /* public function fail($exception = null )
     {
         Log::error('giftJob:'.$exception->getMessage());
     }*/
}
